import "./reset.css";
import editForm from "../form/index.vue";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import { getKeyList } from "@pureadmin/utils";
import { ElMessageBox } from "element-plus";
import { h, computed, onMounted, reactive, ref, type Ref, toRaw } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import type { FormItemProps } from "./types";

export function useSystemSeed(tableRef: Ref) {
  const form = reactive({
    SearchTerm: "",
    OrderBy: ""
  });
  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  // 统计数据
  const totalCount = ref(0);
  const activeCount = ref(0);
  const totalValue = ref(0);

  const columns: TableColumnList = [
    /* {
      label: "勾选列",
      type: "selection",
      fixed: "left",
      reserveSelection: true
    }, */
    {
      label: "ID",
      prop: "Id",
      width: 90
    },
    {
      label: "种子名称",
      prop: "Name",
      minWidth: 130
    },
    {
      label: "种子键",
      prop: "Key",
      minWidth: 130
    },
    {
      label: "种子值",
      prop: "Value",
      minWidth: 130
    },
    {
      label: "种子参数",
      prop: "Params",
      minWidth: 130
    },
    {
      label: "版本",
      prop: "RowVer",
      minWidth: 130
    },
    {
      label: "备注",
      prop: "Comment",
      minWidth: 150
    },
    {
      label: "更新时间",
      prop: "UpdateTime",
      minWidth: 160
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "h-[20px]!",
      "reset-margin",
      "text-gray-500!",
      "dark:text-white!",
      "dark:hover:text-primary!"
    ];
  });
  //获取、搜索系统种子列表
  //获取、搜索系统种子列表
  function onSearch() {
    const paginationInfo = toRaw(pagination);
    loading.value = true;
    const params: any = {
      PageIndex: paginationInfo.currentPage,
      pageSize: paginationInfo.pageSize
    };
    http
      .get(changeHttpLink("/api/Seed"), { params })
      .then((res: any) => {
        loading.value = false;
        if (res.Success) {
          const newData = res.Data.Items;
          dataList.value = newData;
          pagination.total = res.Data.TotalCount;
          // 更新统计数据
          totalCount.value = newData.length; // 总种子数
          // 计算活跃种子数（假设Status为1表示活跃状态，根据实际业务逻辑调整）
          activeCount.value = newData.filter(item => item.Status === 1).length;
          // 计算种子总值
          totalValue.value = newData.reduce(
            (sum, item) => sum + (item.Value || 0),
            0
          );

          setTimeout(() => {
            loading.value = false;
          }, 300);
          console.log(newData);
        } else {
          message(res.Message, { type: "error" });
        }
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }
  //新增、修改
  function openDialog(title, row: any) {
    const id = row?.Id ?? 0;
    addDialog({
      title: `${title}种子`,
      props: {
        formInline: {
          Id: row?.Id ?? 0,
          Key: row.Key ?? 0,
          Value: row.Value ?? 0,
          Name: row?.Name ?? "",
          Params: row?.Params ?? "",
          Comment: row?.Comment ?? "",
          UpdateTime: row?.UpdateTime ?? "",
          RowVer: row?.RowVer ?? 0
        },
        title: title // 传递title属性给表单组件
      },
      width: "640px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(editForm, {
          ref: formRef,
          formInline: null
        }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了种子名称为【${curData.Name}】的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              Id: id,
              Key: curData.Key ?? 0,
              Value: curData.Value ?? 0,
              Name: curData.Name ?? "",
              Params: curData.Params ?? "",
              Comment: curData.Comment ?? "",
              RowVer: curData.RowVer ?? 0
              //seed: 1
            };
            console.log(formData);
            if (title == "创建") {
              console.log(title, formData);
              http
                .post(changeHttpLink("/api/Seed"), {
                  data: formData
                })
                .then((res: any) => {
                  if (res.Success) {
                    chores();
                    onSearch();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  loading.value = false;
                  message(err.message, { type: "error" });
                });
            } else if (title !== "创建") {
              http
                .request("put", changeHttpLink(`/api/Seed/${id}`), {
                  data: formData
                })
                .then((res: any) => {
                  console.log("res", res);
                  if (res.Success) {
                    chores();
                    onSearch();
                  } else {
                    message(res.Message, { type: "error" });
                  }
                  loading.value = false;
                })
                .catch(err => {
                  message(err.message, { type: "error" });
                  loading.value = false;
                });
            }
          }
        });
      }
    });
  }
  //种子数据删除
  function handleDelete(row) {
    http
      .request("delete", changeHttpLink(`/api/Seed/${row.Id}`), {
        data: row.Id
      })
      .then((res: any) => {
        console.log(res);
        if (res.Success) {
          message(`您删除了种子名称为${row.Name}的这条数据`, {
            type: "success"
          });
          onSearch();
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
        console.error(err);
      });
  }
  /** 批量删除 */
  function onbatchDel() {
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    const params = {
      ids: curSelected.map(item => {
        return item.Id;
      })
    };
    /* const ids = curSelected.map(item => {
        return item.Id;
      }); */
    console.log(params);
    http
      .request("post", changeHttpLink("/api/Seed/batch-delete"), {
        data: params
      })
      .then((res: any) => {
        console.log(res);
        if (res.Success) {
          message(
            `您删除了ID为【 ${getKeyList(curSelected, "Id")}】的${curSelected.length}条数据`,
            {
              type: "success"
            }
          );
          tableRef.value.getTableRef().clearSelection();
          onSearch();
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
        console.error(err);
      });
  }
  //重置种子
  function handleReset(row) {
    ElMessageBox.confirm(`确认要重置ID为${row.Id}的种子值吗?`, "系统提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      draggable: true
    })
      .then(() => {
        loading.value = true;
        http
          .request("patch", changeHttpLink(`/api/Seed/reset/${row.Id}`), {
            data: {
              id: row.id
            }
          })
          .then((res: any) => {
            loading.value = false;
            if (res.Success) {
              message(`已重置ID为${row.Id}的种子值`, { type: "success" });
              onSearch();
            } else {
              message(res.Message, { type: "error" });
            }
          })
          .catch(err => {
            loading.value = false;
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        // 取消操作
      });
  }
  //分页变化
  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    dataList.value = [];
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val) {
    selectedNum.value = val.length;
    tableRef.value.setAdaptive();
  }
  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    tableRef.value.getTableRef().clearSelection();
  }
  //重置表单
  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }
  // 设备检测
  function deviceDetection() {
    return window.innerWidth < 1024;
  }
  onMounted(() => {
    onSearch();
  });

  return {
    form,
    formRef,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleDelete,
    handleReset,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange,
    totalCount,
    activeCount,
    totalValue
  };
}
